package com.tianji.learning.mq.listeners;


import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
@RequiredArgsConstructor
public class LessonRefundListener {
    private final ILearningLessonService learningLessonService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConstants.Queue.LEARNING_LESSON_REFUND_QUEUE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void listenOrderRefund(OrderBasicDTO order) {
        // 1.健壮性处理
        if (order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())) {
            // 数据有误，无需处理
            log.error("接收到MQ消息有误");
            return;
        }
        Long userId = order.getUserId();
        Long courseId = order.getCourseIds().get(0);
        // 2.删除对应课程
        log.debug("需要删除的课程对应信息：userId:{};courseId:{}", userId, courseId);
        learningLessonService.deleteMyLessonCourse(userId, courseId);
    }

}



